package com.qeng.aiwanba.util;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;

import com.qeng.aiwanba.R;
import com.qeng.aiwanba.download.DownloadManager;
import com.qeng.aiwanba.download.DownloadService;
import com.qeng.aiwanba.model.AppData;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.List;

/**
 * Created by lixy on 2017/9/27.
 */

public class DownloadUtil {
    static final int ALL_DOWNLOAD_PAUSE = 0;
    static final int ALL_DOWNLOAD_CONTINUE = 1;
    static final int ALL_DOWNLOAD_RESTART = 2;
    static final int ALL_DOWNLOAD_DELETE = 3;

    public static boolean addDownloadInfo(Context context, AppData data, int networkType) {
        Cursor cursor = queryDownloadByPackageName(context, data.getPackageName());
        if (cursor != null && cursor.getCount() > 0) {
            Util.showToast(context,context.getString(R.string.tip_alredy_download_task_list));
            cursor.close();
            return false;
        }else{
            Uri srcUri = Uri.parse(data.getDownloadUrl());
            DownloadManager.Request request = new DownloadManager.Request(srcUri);
            request.setDestinationInExternalPublicDir(
                    Environment.DIRECTORY_DOWNLOADS, "/");
            request.setTitle(data.getPackageName());
            request.setDescription(data.getData());
            request.setAllowedNetworkTypes(networkType);
            request.setMimeType(data.getPackageName());
            DownloadManager.getInstance(context).enqueue(request);
        }
        return true;
    }

    public static Cursor queryDownloadByPackageName(Context context,String packageName){
        DownloadManager mDownloadManager = DownloadManager.getInstance(context);
        mDownloadManager.setAccessAllDownloads(true);
        DownloadManager.Query baseQuery = new DownloadManager.Query()
                .setOnlyIncludeVisibleInDownloadsUi(true);
        return mDownloadManager.query(baseQuery.setFilterByMimeType(packageName));
    }

    public static Double getProgressValue(Context context,String packageName) {
        Cursor mCursor = queryDownloadByTitle(context,packageName);
        if(mCursor != null && mCursor.getCount()>0) {
            mCursor.moveToFirst();
            int totalBytesId = mCursor
                    .getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
            int currentBytesId = mCursor
                    .getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);

            Double result = (Double.valueOf(mCursor.getLong(currentBytesId) * 100) / Double.valueOf(mCursor.getLong(totalBytesId)));
            mCursor.close();

            return result;
        }
        return null;
    }

    public static Cursor queryDownloadByTitle(Context context,String title){
        DownloadManager mDownloadManager = DownloadManager.getInstance(context);
        mDownloadManager.setAccessAllDownloads(true);
        DownloadManager.Query baseQuery = new DownloadManager.Query()
                .setOnlyIncludeVisibleInDownloadsUi(true);
        return mDownloadManager.query(baseQuery.setFilterByTitle(title));
    }

    public static Cursor queryAllDownload(Context context){
        DownloadManager mDownloadManager = DownloadManager.getInstance(context);
        mDownloadManager.setAccessAllDownloads(true);
        DownloadManager.Query baseQuery = new DownloadManager.Query()
                .setOnlyIncludeVisibleInDownloadsUi(true);
        return mDownloadManager.query(baseQuery);
    }

    //继续下载
    public static void resumeDownload(Context context,String packageName){
        startDownloadService(context);
        long downloadId = getDownloadIdByPackageName(context,packageName);
        if(downloadId != -1){
            DownloadManager downloadManager = DownloadManager.getInstance(context);
            downloadManager.resumeDownload(downloadId);
        }else{
            try {
                throw new Exception("未找到此下载任务");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //重试下载
    public static void restartDownload(Context context,String packageName){
        startDownloadService(context);
        long downloadId = getDownloadIdByPackageName(context,packageName);
        if(downloadId != -1){
            DownloadManager downloadManager = DownloadManager.getInstance(context);
            downloadManager.restartDownload(downloadId);
        }else{
            try {
                throw new Exception("未找到此下载任务");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //暂停下载
    public static void pauseDownload(Context context,String packageName){
        long downloadId = getDownloadIdByPackageName(context,packageName);
        if(downloadId != -1){
            DownloadManager downloadManager = DownloadManager.getInstance(context);
            downloadManager.pauseDownload(downloadId);
        }else{
            try {
                throw new Exception("未找到此下载任务");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //删除下载任务
    public static void deleteDownload(Context context,String packageName){
        long downloadId = getDownloadIdByPackageName(context,packageName);
        if(downloadId != -1){
            DownloadManager downloadManager = DownloadManager.getInstance(context);
//            downloadManager.markRowDeleted(downloadId);
            downloadManager.remove(downloadId);
        }else{
            try {
                throw new Exception("未找到此下载任务");
            } catch (Exception e) {
//                e.printStackTrace();
            }
        }
    }

    //获取下载任务
    public static String getDownloadTask(Context context,String packageName){
        Cursor mCursor = queryDownloadByTitle(context,packageName);
        if(mCursor != null && mCursor.getCount()>0) {
            mCursor.moveToFirst();
            String result = getDownloadTask(mCursor).toString();
            mCursor.close();
            return result;
        }else{
            try {
                throw new Exception("未找到此下载任务");
            } catch (Exception e) {
//                e.printStackTrace();
            }
        }
        if(mCursor!=null)
            mCursor.close();
        return null;
    }

    private static JSONObject getDownloadTask(Cursor mCursor){
        String data = mCursor.getString(mCursor.getColumnIndexOrThrow(DownloadManager.COLUMN_DESCRIPTION));
        long totalBytes = mCursor.getLong(mCursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
        long currentBytes = mCursor.getLong(mCursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
        int state = getDownloadState(mCursor);
        JSONObject object = new JSONObject();
        try {
            if(totalBytes == -1){
                totalBytes = 0;
                object.put("progress", 0);
            }else {
                String progress = new DecimalFormat("#.0").format(Double.valueOf(currentBytes*100)/Double.valueOf(totalBytes));
                object.put("progress",progress.startsWith(".")?"0"+progress:progress);
            }
            object.put("packageName",mCursor.getString(mCursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TITLE)));
            object.put("fileSizeRaw",totalBytes);
            object.put("fileSize",Util.formatFileSize(totalBytes));
            object.put("downloadSizeRaw",currentBytes);
            object.put("downloadSize",Util.formatFileSize(currentBytes));
            object.put("status",state);
            object.put("data",data);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return object;
    }

    //获取全部的下在任务
    public static String getAllDownloadTask(Context context){
        Cursor mCursor = queryAllDownload(context);
        JSONArray jsonArray = new JSONArray();
        for(mCursor.moveToFirst();!mCursor.isAfterLast();mCursor.moveToNext()){
            jsonArray.put(getDownloadTask(mCursor));
        }
        if(mCursor != null){
            mCursor.close();
        }
        return jsonArray.toString();
    }

    //获取当前任务下载状态
    public static int getDownloadState(Context context,String packageName){
        Cursor mCursor = queryDownloadByTitle(context,packageName);
        if(mCursor != null && mCursor.getCount()>0) {
            mCursor.moveToFirst();
            int result = getDownloadState(mCursor);
            mCursor.close();
            return result;
        }
        if(mCursor!=null){
            mCursor.close();
        }
        return -1;
    }

    public static int getDownloadState(Cursor mCursor){
        int state = mCursor.getInt(mCursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS));
        switch (state){
            case DownloadManager.STATUS_FAILED:
                return 4;
            case DownloadManager.STATUS_PAUSED:
                return 2;
            case DownloadManager.STATUS_PENDING:
                return 5;
            case DownloadManager.STATUS_RUNNING:
                return 3;
            case DownloadManager.STATUS_SUCCESSFUL:
                return 1;
        }
        return -1;
    }
    

    public static long getDownloadIdByPackageName(Context context,String packageName){
        Cursor mCursor = queryDownloadByTitle(context,packageName);
        if(mCursor != null && mCursor.getCount()>0) {
            mCursor.moveToFirst();
            long downloadId = mCursor.getLong(mCursor.getColumnIndexOrThrow(DownloadManager.COLUMN_ID));
            mCursor.close();
            return downloadId;
        }
        return -1;
    }

    public static String getPathByPackageName(Context context,String packageName){
        Cursor mCursor = queryDownloadByTitle(context,packageName);
        if(mCursor != null && mCursor.getCount()>0) {
            mCursor.moveToFirst();
            String result = mCursor.getString(mCursor.getColumnIndexOrThrow(DownloadManager.COLUMN_LOCAL_URI));
            mCursor.close();
            return result;
        }
        if(mCursor!=null){
            mCursor.close();
        }
        return null;
    }


    private static void startDownloadService(Context context){
        if(!isServiceWork(context,"com.qeng.aiwanba.download.DownloadService")){
            context.startService(new Intent(context, DownloadService.class));
        }
    }

    private static boolean isServiceWork(Context mContext, String serviceName) {
        boolean isWork = false;
        ActivityManager myAM = (ActivityManager) mContext
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> myList = myAM.getRunningServices(40);
        if (myList.size() <= 0) {
            return false;
        }
        for (int i = 0; i < myList.size(); i++) {
            String mName = myList.get(i).service.getClassName().toString();
            if (mName.equals(serviceName)) {
                isWork = true;
                break;
            }
        }
        return isWork;
    }

    public static void editAllDownloadState(Context context,int state){
        DownloadManager mDownloadManager = DownloadManager.getInstance(context);
        mDownloadManager.setAccessAllDownloads(true);
        DownloadManager.Query baseQuery = new DownloadManager.Query()
                .setOnlyIncludeVisibleInDownloadsUi(true);
        Cursor cursor = mDownloadManager.query(baseQuery);
        if(cursor != null && cursor.getCount()>0) {
            for(cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext()) {
                long id = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_ID));
                switch (state){
                    case ALL_DOWNLOAD_PAUSE:
                        //全部暂停
                        if(cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS))==DownloadManager.STATUS_RUNNING) {
                            mDownloadManager.pauseDownload(id);
                        }
                        break;
                    case ALL_DOWNLOAD_CONTINUE:
                        //全部继续
                        if(cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS))==DownloadManager.STATUS_PAUSED) {
                            mDownloadManager.resumeDownload(id);
                        }
                        break;
                    case ALL_DOWNLOAD_RESTART:
                        //全部重试
                        if(cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS))==DownloadManager.STATUS_FAILED) {
                            mDownloadManager.restartDownload(id);
                        }
                        break;
                    case ALL_DOWNLOAD_DELETE:
                        //全部删除
                        mDownloadManager.remove(id);
                        break;
                }
            }
            cursor.close();
        }
    }


}
